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:
parent
040870770d
commit
61150c5063
253 changed files with 1009 additions and 1210 deletions
|
|
@ -13,7 +13,7 @@ public class App {
|
|||
private static final Logger logger = LoggerFactory.getLogger(App.class);
|
||||
private static volatile boolean shutdownRequested = false;
|
||||
|
||||
public static void main(String[] args) {
|
||||
public static void main(final String[] args) {
|
||||
Thread shutdownHook =
|
||||
new Thread(
|
||||
() -> {
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ public class ReadyListener extends ListenerAdapter {
|
|||
private static final Logger logger = LoggerFactory.getLogger(ReadyListener.class);
|
||||
|
||||
@Override
|
||||
public void onReady(ReadyEvent event) {
|
||||
public void onReady(final ReadyEvent event) {
|
||||
LoggerDecorator.success(
|
||||
logger, "Бот " + event.getJDA().getSelfUser().getName() + " успешно запущен!");
|
||||
LoggerDecorator.bot(logger, "Подключен к " + event.getGuildTotalCount() + " серверам");
|
||||
|
|
|
|||
|
|
@ -19,12 +19,12 @@ public final class ConfigLoader {
|
|||
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);
|
||||
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;
|
||||
try {
|
||||
int port = Integer.parseInt(raw.trim());
|
||||
|
|
|
|||
|
|
@ -120,7 +120,7 @@ public class BotInitializer {
|
|||
return buildWithLavalink(builder, ml);
|
||||
}
|
||||
|
||||
private JDA createRadioJDA(LavalinkManager radioLavalink) {
|
||||
private JDA createRadioJDA(final LavalinkManager radioLavalink) {
|
||||
if (config.getRadioToken() == null || config.getRadioToken().isBlank()) return null;
|
||||
LoggerDecorator.startup(logger, "Инициализация radio бота...");
|
||||
var builder =
|
||||
|
|
@ -134,7 +134,7 @@ public class BotInitializer {
|
|||
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) {
|
||||
builder.setVoiceDispatchInterceptor(new JDAVoiceUpdateListener(ll.getClient()));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,19 +9,19 @@ public class BotJdaRegistry {
|
|||
private JDA music;
|
||||
private JDA radio;
|
||||
|
||||
public void setMain(JDA jda) {
|
||||
public void setMain(final JDA jda) {
|
||||
this.main = jda;
|
||||
}
|
||||
|
||||
public void setMusic(JDA jda) {
|
||||
public void setMusic(final JDA jda) {
|
||||
this.music = jda;
|
||||
}
|
||||
|
||||
public void setRadio(JDA jda) {
|
||||
public void setRadio(final JDA jda) {
|
||||
this.radio = jda;
|
||||
}
|
||||
|
||||
public JDA getByPersonality(String personality) {
|
||||
public JDA getByPersonality(final String personality) {
|
||||
return switch (personality) {
|
||||
case "windows" -> music != null ? music : main;
|
||||
case "gentoo" -> radio != null ? radio : main;
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ public class EventDispatcher implements Lifecycle {
|
|||
this.metrics = metrics;
|
||||
}
|
||||
|
||||
public void handleMessage(MessageReceivedEvent event) {
|
||||
public void handleMessage(final MessageReceivedEvent event) {
|
||||
// Игнорируем ботов
|
||||
if (event.getAuthor().isBot()) {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import net.dv8tion.jda.api.utils.cache.CacheFlag;
|
|||
public final class 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)
|
||||
.setStatus(OnlineStatus.ONLINE)
|
||||
.setActivity(Activity.playing(activity))
|
||||
|
|
@ -20,7 +20,7 @@ public final class JdaFactory {
|
|||
.enableCache(CacheFlag.VOICE_STATE);
|
||||
}
|
||||
|
||||
public static JDA awaitJda(JDA jda) {
|
||||
public static JDA awaitJda(final JDA jda) {
|
||||
try {
|
||||
jda.awaitReady();
|
||||
} catch (InterruptedException e) {
|
||||
|
|
|
|||
|
|
@ -7,8 +7,7 @@ import creator.loki.feature.music.repository.QueueRepository;
|
|||
public final class LavalinkManagerFactory {
|
||||
private LavalinkManagerFactory() {}
|
||||
|
||||
public static LavalinkManager create(
|
||||
BotConfig config, QueueRepository queueRepository, String token) {
|
||||
public static LavalinkManager create(final BotConfig config, final QueueRepository queueRepository, final String token) {
|
||||
return new LavalinkManager(config, queueRepository, token);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,31 +31,7 @@ public class ListenerAggregator {
|
|||
private final Object[] listeners;
|
||||
|
||||
@Inject
|
||||
public ListenerAggregator(
|
||||
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) {
|
||||
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) {
|
||||
this.listeners =
|
||||
new Object[] {
|
||||
readyListener,
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ public class MessageCache extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onMessageReceived(MessageReceivedEvent event) {
|
||||
public void onMessageReceived(final MessageReceivedEvent event) {
|
||||
if (event.getAuthor().isBot()) return;
|
||||
String content = event.getMessage().getContentRaw();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ public class ShutdownManager {
|
|||
this.radioManager = radioManager;
|
||||
}
|
||||
|
||||
public void shutdown(JDA jda) {
|
||||
public void shutdown(final JDA jda) {
|
||||
shutdown(new BotCluster(jda, null, null));
|
||||
}
|
||||
|
||||
|
|
@ -35,7 +35,7 @@ public class ShutdownManager {
|
|||
shutdown(new BotCluster(null, null, null));
|
||||
}
|
||||
|
||||
public void shutdown(BotCluster cluster) {
|
||||
public void shutdown(final BotCluster cluster) {
|
||||
logger.info("========================================");
|
||||
logger.info("Получен сигнал завершения работы ботов...");
|
||||
logger.info("========================================");
|
||||
|
|
@ -70,7 +70,7 @@ public class ShutdownManager {
|
|||
LoggerDecorator.success(logger, "Боты успешно завершены!");
|
||||
}
|
||||
|
||||
private void shutdownJDA(JDA jda, String name) {
|
||||
private void shutdownJDA(final JDA jda, final String name) {
|
||||
LoggerDecorator.bot(logger, "Отключение " + name + " JDA...");
|
||||
jda.shutdown();
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ public class CommandException extends Exception {
|
|||
this.userMessage = userMessage;
|
||||
}
|
||||
|
||||
public CommandException(String userMessage, Throwable cause) {
|
||||
public CommandException(String userMessage, final Throwable cause) {
|
||||
super(userMessage, cause);
|
||||
this.userMessage = userMessage;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ public class CommandExceptionHandler {
|
|||
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);
|
||||
|
||||
String userMessage;
|
||||
|
|
@ -43,8 +43,7 @@ public class CommandExceptionHandler {
|
|||
}
|
||||
|
||||
/** Обрабатывает исключение с кастомным сообщением */
|
||||
public static void handle(
|
||||
Throwable throwable, MessageChannel channel, String commandName, String customMessage) {
|
||||
public static void handle(final Throwable throwable, final MessageChannel channel, final String commandName, final String customMessage) {
|
||||
LoggerDecorator.error(logger, "Ошибка при выполнении команды: " + commandName, throwable);
|
||||
|
||||
MessageEmbed errorEmbed =
|
||||
|
|
|
|||
|
|
@ -2,5 +2,5 @@ package creator.loki.core.registry;
|
|||
|
||||
@FunctionalInterface
|
||||
public interface CommandRegistrar {
|
||||
void register(CommandRegistry registry);
|
||||
void register(final CommandRegistry registry);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ public class CommandRegistry {
|
|||
private static final Logger logger = LoggerFactory.getLogger(CommandRegistry.class);
|
||||
private final Map<String, Command> commands = new HashMap<>();
|
||||
|
||||
public void register(Command command) {
|
||||
public void register(final Command command) {
|
||||
String key = command.getName().toLowerCase();
|
||||
Command previous = commands.put(key, command);
|
||||
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());
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ public class CooldownManager implements Lifecycle {
|
|||
}
|
||||
|
||||
/** Проверяет, находится ли пользователь на cooldown для команды */
|
||||
public boolean isOnCooldown(String userId, String commandName) {
|
||||
public boolean isOnCooldown(final String userId, final String commandName) {
|
||||
String key = userId + ":" + commandName;
|
||||
Instant cooldownEnd = cooldowns.get(key);
|
||||
|
||||
|
|
@ -37,7 +37,7 @@ public class CooldownManager implements Lifecycle {
|
|||
}
|
||||
|
||||
/** Возвращает оставшееся время cooldown в секундах */
|
||||
public long getRemainingSeconds(String userId, String commandName) {
|
||||
public long getRemainingSeconds(final String userId, final String commandName) {
|
||||
String key = userId + ":" + commandName;
|
||||
Instant cooldownEnd = cooldowns.get(key);
|
||||
|
||||
|
|
@ -50,7 +50,7 @@ public class CooldownManager implements Lifecycle {
|
|||
}
|
||||
|
||||
/** Применяет 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;
|
||||
Instant cooldownEnd = Instant.now().plusSeconds(seconds);
|
||||
cooldowns.put(key, cooldownEnd);
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ public class RateLimiter implements Lifecycle {
|
|||
}
|
||||
|
||||
/** Проверяет, может ли пользователь выполнить действие */
|
||||
public boolean allowUser(String userId) {
|
||||
public boolean allowUser(final String userId) {
|
||||
TokenBucket bucket =
|
||||
userBuckets.computeIfAbsent(
|
||||
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 =
|
||||
guildBuckets.computeIfAbsent(
|
||||
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);
|
||||
}
|
||||
|
||||
/** Возвращает оставшееся время до восстановления для пользователя (в секундах) */
|
||||
public long getUserWaitTime(String userId) {
|
||||
public long getUserWaitTime(final String userId) {
|
||||
TokenBucket bucket = userBuckets.get(userId);
|
||||
if (bucket == null) {
|
||||
return 0;
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ public class Database implements Lifecycle {
|
|||
+ config.getMaximumPoolSize()
|
||||
+ ")");
|
||||
|
||||
try (Connection conn = dataSource.getConnection();
|
||||
try (final Connection conn = dataSource.getConnection();
|
||||
Statement stmt = conn.createStatement()) {
|
||||
stmt.execute("PRAGMA foreign_keys = ON");
|
||||
} catch (SQLException e) {
|
||||
|
|
@ -57,8 +57,8 @@ public class Database implements Lifecycle {
|
|||
}
|
||||
}
|
||||
|
||||
public void execute(String sql) {
|
||||
try (Connection conn = getConnection();
|
||||
public void execute(final String sql) {
|
||||
try (final Connection conn = getConnection();
|
||||
Statement stmt = conn.createStatement()) {
|
||||
stmt.execute(sql);
|
||||
} 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;
|
||||
try {
|
||||
conn = getConnection();
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ public class DatabaseMigration {
|
|||
this.database = database;
|
||||
}
|
||||
|
||||
public void migrateFromJson(String jsonPath) {
|
||||
public void migrateFromJson(final String jsonPath) {
|
||||
LoggerDecorator.database(logger, "Начало миграции данных из JSON: " + jsonPath);
|
||||
if (!new java.io.File(jsonPath).exists()) {
|
||||
logger.info("No legacy data file found at {}, skipping migration", jsonPath);
|
||||
|
|
@ -49,7 +49,7 @@ public class DatabaseMigration {
|
|||
}
|
||||
|
||||
@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)) {
|
||||
var type = new TypeToken<Map<String, Object>>() {}.getType();
|
||||
return (Map<String, Object>) gson.fromJson(reader, type);
|
||||
|
|
@ -60,7 +60,7 @@ public class DatabaseMigration {
|
|||
}
|
||||
|
||||
@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");
|
||||
if (userStats == null) return;
|
||||
LoggerDecorator.database(logger, "Миграция userStats: " + userStats.size() + " записей");
|
||||
|
|
@ -85,7 +85,7 @@ public class DatabaseMigration {
|
|||
}
|
||||
|
||||
@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");
|
||||
if (reputation == null) return;
|
||||
LoggerDecorator.database(logger, "Миграция reputation: " + reputation.size() + " записей");
|
||||
|
|
@ -103,7 +103,7 @@ public class DatabaseMigration {
|
|||
}
|
||||
|
||||
@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");
|
||||
if (shipPairs == null) return;
|
||||
LoggerDecorator.database(logger, "Миграция shipPairs: " + shipPairs.size() + " записей");
|
||||
|
|
@ -126,7 +126,7 @@ public class DatabaseMigration {
|
|||
}
|
||||
|
||||
@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");
|
||||
if (customRoles == null) return;
|
||||
LoggerDecorator.database(logger, "Миграция custom_roles");
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ import creator.loki.feature.ship.repository.ShipPairRepository;
|
|||
public class DatabaseModule extends AbstractModule {
|
||||
@Provides
|
||||
@Singleton
|
||||
Database provideDatabase(BotConfig config) {
|
||||
Database provideDatabase(final BotConfig config) {
|
||||
Database database = new Database(config.getDbPath());
|
||||
database.connect();
|
||||
new DatabaseSchema(database).createTables();
|
||||
|
|
@ -25,37 +25,37 @@ public class DatabaseModule extends AbstractModule {
|
|||
|
||||
@Provides
|
||||
@Singleton
|
||||
ConfigRepository provideConfigRepository(Database database) {
|
||||
ConfigRepository provideConfigRepository(final Database database) {
|
||||
return new ConfigRepository(database);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
GuildConfigRepository provideGuildConfigRepository(ConfigRepository cr) {
|
||||
GuildConfigRepository provideGuildConfigRepository(final ConfigRepository cr) {
|
||||
return new PrefixedGuildConfigRepository(cr);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
RatingsRepository provideRatingsRepository(Database database) {
|
||||
RatingsRepository provideRatingsRepository(final Database database) {
|
||||
return new RatingsRepository(database);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
ReputationRepository provideReputationRepository(Database database) {
|
||||
ReputationRepository provideReputationRepository(final Database database) {
|
||||
return new ReputationRepository(database);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
ShipPairRepository provideShipPairRepository(Database database) {
|
||||
ShipPairRepository provideShipPairRepository(final Database database) {
|
||||
return new ShipPairRepository(database);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
QueueRepository provideQueueRepository(Database database) {
|
||||
QueueRepository provideQueueRepository(final Database database) {
|
||||
return new QueueRepository(database);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import creator.loki.database.Database;
|
|||
|
||||
public final class CoreTables {
|
||||
|
||||
public static void create(Database database) {
|
||||
public static void create(final Database database) {
|
||||
createConfig(database);
|
||||
createUserStats(database);
|
||||
createReputation(database);
|
||||
|
|
@ -12,7 +12,7 @@ public final class CoreTables {
|
|||
createIndexes(database);
|
||||
}
|
||||
|
||||
private static void createConfig(Database database) {
|
||||
private static void createConfig(final Database database) {
|
||||
database.execute(
|
||||
"""
|
||||
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(
|
||||
"""
|
||||
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(
|
||||
"""
|
||||
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(
|
||||
"""
|
||||
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_total_xp ON user_stats(total_xp DESC)");
|
||||
|
|
|
|||
|
|
@ -134,7 +134,7 @@ public final class FeatureTables {
|
|||
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(MUSIC_QUEUE);
|
||||
database.execute(WARNINGS);
|
||||
|
|
@ -150,7 +150,7 @@ public final class FeatureTables {
|
|||
createIndexes(database);
|
||||
}
|
||||
|
||||
private static void createIndexes(Database database) {
|
||||
private static void createIndexes(final Database database) {
|
||||
for (var sql :
|
||||
new String[] {
|
||||
"CREATE INDEX IF NOT EXISTS idx_ratings_guild_type ON ratings(guild_id, rating_type)",
|
||||
|
|
|
|||
|
|
@ -80,11 +80,7 @@ public class BotModule extends AbstractModule {
|
|||
|
||||
@Provides
|
||||
@Singleton
|
||||
EventDispatcher provideEventDispatcher(
|
||||
BotConfig config,
|
||||
CommandRegistry registry,
|
||||
RateLimiter rateLimiter,
|
||||
MetricsCollector metrics) {
|
||||
EventDispatcher provideEventDispatcher(final BotConfig config, final CommandRegistry registry, final RateLimiter rateLimiter, final MetricsCollector metrics) {
|
||||
return new EventDispatcher(config, registry, rateLimiter, metrics);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,57 +17,57 @@ public class EmbedFactory {
|
|||
return new EmbedFactory();
|
||||
}
|
||||
|
||||
public EmbedFactory withTitle(String title) {
|
||||
public EmbedFactory withTitle(final String title) {
|
||||
builder.setTitle(title);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EmbedFactory withDescription(String description) {
|
||||
public EmbedFactory withDescription(final String description) {
|
||||
builder.setDescription(description);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EmbedFactory withColor(Color color) {
|
||||
public EmbedFactory withColor(final Color color) {
|
||||
builder.setColor(color);
|
||||
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);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EmbedFactory withFooter(String text) {
|
||||
public EmbedFactory withFooter(final String text) {
|
||||
builder.setFooter(text);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EmbedFactory withFooter(String text, String iconUrl) {
|
||||
public EmbedFactory withFooter(final String text, final String iconUrl) {
|
||||
builder.setFooter(text, iconUrl);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EmbedFactory withThumbnail(String url) {
|
||||
public EmbedFactory withThumbnail(final String url) {
|
||||
builder.setThumbnail(url);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EmbedFactory withImage(String url) {
|
||||
public EmbedFactory withImage(final String url) {
|
||||
builder.setImage(url);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EmbedFactory withAuthor(String name) {
|
||||
public EmbedFactory withAuthor(final String name) {
|
||||
builder.setAuthor(name);
|
||||
return this;
|
||||
}
|
||||
|
||||
public EmbedFactory withAuthor(String name, String url) {
|
||||
public EmbedFactory withAuthor(final String name, final String url) {
|
||||
builder.setAuthor(name, url);
|
||||
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);
|
||||
return this;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
.setColor(Color.GREEN)
|
||||
.setTitle("✅ " + title)
|
||||
|
|
@ -21,7 +21,7 @@ public final class EmbedTemplates {
|
|||
.build();
|
||||
}
|
||||
|
||||
public static MessageEmbed error(String title, String description) {
|
||||
public static MessageEmbed error(final String title, final String description) {
|
||||
return new EmbedBuilder()
|
||||
.setColor(Color.RED)
|
||||
.setTitle("❌ " + title)
|
||||
|
|
@ -30,7 +30,7 @@ public final class EmbedTemplates {
|
|||
.build();
|
||||
}
|
||||
|
||||
public static MessageEmbed info(String title, String description) {
|
||||
public static MessageEmbed info(final String title, final String description) {
|
||||
return new EmbedBuilder()
|
||||
.setColor(Color.CYAN)
|
||||
.setTitle("ℹ️ " + title)
|
||||
|
|
@ -39,7 +39,7 @@ public final class EmbedTemplates {
|
|||
.build();
|
||||
}
|
||||
|
||||
public static MessageEmbed warning(String title, String description) {
|
||||
public static MessageEmbed warning(final String title, final String description) {
|
||||
return new EmbedBuilder()
|
||||
.setColor(Color.ORANGE)
|
||||
.setTitle("⚠️ " + title)
|
||||
|
|
|
|||
|
|
@ -69,20 +69,19 @@ public final class HelpCategories {
|
|||
|
||||
private HelpCategories() {}
|
||||
|
||||
public static String getEmoji(String category) {
|
||||
public static String getEmoji(final String 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));
|
||||
}
|
||||
|
||||
public static String getDescription(String category) {
|
||||
public static String getDescription(final String category) {
|
||||
return DESCRIPTIONS.getOrDefault(category, "Команды категории");
|
||||
}
|
||||
|
||||
public static boolean isCategoryVisible(
|
||||
String category, boolean isAdmin, boolean isSuper, boolean isNsfwChannel) {
|
||||
public static boolean isCategoryVisible(final String category, final boolean isAdmin, final boolean isSuper, final boolean isNsfwChannel) {
|
||||
if (CommandCategories.SETTINGS.equals(category) && !isAdmin) {
|
||||
return false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ public class GenerateRatingsCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
if (!config.getSuperAdminId().equals(context.getAuthor().getUser().getId())) {
|
||||
context
|
||||
.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;
|
||||
var value =
|
||||
switch (ratingType) {
|
||||
|
|
@ -110,7 +110,7 @@ public class GenerateRatingsCommand implements Command {
|
|||
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()
|
||||
.withTitle(title)
|
||||
.withDescription(description)
|
||||
|
|
@ -118,7 +118,7 @@ public class GenerateRatingsCommand implements Command {
|
|||
.build();
|
||||
}
|
||||
|
||||
private MessageEmbed warnEmbed(String title, String description) {
|
||||
private MessageEmbed warnEmbed(final String title, final String description) {
|
||||
return EmbedFactory.create()
|
||||
.withTitle(title)
|
||||
.withDescription(description)
|
||||
|
|
@ -126,7 +126,7 @@ public class GenerateRatingsCommand implements Command {
|
|||
.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()
|
||||
.withTitle("✅ Генерация завершена")
|
||||
.withDescription(
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ public class SetupSlashHandler extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onGuildReady(@NotNull GuildReadyEvent event) {
|
||||
public void onGuildReady(@NotNull final GuildReadyEvent event) {
|
||||
if (registered) return;
|
||||
registered = true;
|
||||
event.getJDA().updateCommands()
|
||||
|
|
@ -51,14 +51,14 @@ public class SetupSlashHandler extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) {
|
||||
public void onSlashCommandInteraction(@NotNull final SlashCommandInteractionEvent event) {
|
||||
if (!event.getName().equals("setup")) return;
|
||||
event.deferReply().queue();
|
||||
showDashboard(event.getGuild(), event.getHook());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onButtonInteraction(@NotNull ButtonInteractionEvent event) {
|
||||
public void onButtonInteraction(@NotNull final ButtonInteractionEvent event) {
|
||||
String id = event.getComponentId();
|
||||
if (!id.startsWith("setup_")) return;
|
||||
event.deferEdit().queue();
|
||||
|
|
@ -76,7 +76,7 @@ public class SetupSlashHandler extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onEntitySelectInteraction(@NotNull EntitySelectInteractionEvent event) {
|
||||
public void onEntitySelectInteraction(@NotNull final EntitySelectInteractionEvent event) {
|
||||
String id = event.getComponentId();
|
||||
if (!id.startsWith("setup_")) return;
|
||||
event.deferEdit().queue();
|
||||
|
|
@ -109,7 +109,7 @@ public class SetupSlashHandler extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent event) {
|
||||
public void onStringSelectInteraction(@NotNull final StringSelectInteractionEvent event) {
|
||||
String id = event.getComponentId();
|
||||
if (!id.startsWith("setup_")) return;
|
||||
event.deferEdit().queue();
|
||||
|
|
@ -122,7 +122,7 @@ public class SetupSlashHandler extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onModalInteraction(@NotNull ModalInteractionEvent event) {
|
||||
public void onModalInteraction(@NotNull final ModalInteractionEvent event) {
|
||||
String id = event.getModalId();
|
||||
if (!id.startsWith("setup_")) return;
|
||||
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())
|
||||
.setComponents(buildDashboardButtons())
|
||||
.queue();
|
||||
}
|
||||
|
||||
private void showVoicePanel(Guild guild, InteractionHook hook) {
|
||||
private void showVoicePanel(Guild guild, final InteractionHook hook) {
|
||||
EmbedBuilder embed = new EmbedBuilder()
|
||||
.setTitle("🎤 Настройка голосовых каналов")
|
||||
.setColor(BLURPLE);
|
||||
|
|
@ -183,7 +183,7 @@ public class SetupSlashHandler extends ListenerAdapter {
|
|||
.queue();
|
||||
}
|
||||
|
||||
private void showCounterPanel(Guild guild, InteractionHook hook) {
|
||||
private void showCounterPanel(Guild guild, final InteractionHook hook) {
|
||||
EmbedBuilder embed = new EmbedBuilder()
|
||||
.setTitle("📊 Настройка счётчика участников")
|
||||
.setColor(BLURPLE);
|
||||
|
|
@ -210,7 +210,7 @@ public class SetupSlashHandler extends ListenerAdapter {
|
|||
.queue();
|
||||
}
|
||||
|
||||
private void showLoggingPanel(Guild guild, InteractionHook hook) {
|
||||
private void showLoggingPanel(Guild guild, final InteractionHook hook) {
|
||||
EmbedBuilder embed = new EmbedBuilder()
|
||||
.setTitle("📝 Настройка логирования")
|
||||
.setColor(BLURPLE);
|
||||
|
|
@ -235,7 +235,7 @@ public class SetupSlashHandler extends ListenerAdapter {
|
|||
.queue();
|
||||
}
|
||||
|
||||
private void showLevelRolesPanel(Guild guild, InteractionHook hook) {
|
||||
private void showLevelRolesPanel(Guild guild, final InteractionHook hook) {
|
||||
Map<String, String> allConfig = configRepo.getAll();
|
||||
var levelRoles = allConfig.entrySet().stream()
|
||||
.filter(e -> e.getKey().startsWith("level_role_"))
|
||||
|
|
@ -269,7 +269,7 @@ public class SetupSlashHandler extends ListenerAdapter {
|
|||
.queue();
|
||||
}
|
||||
|
||||
private void openCounterFormatModal(ButtonInteractionEvent event) {
|
||||
private void openCounterFormatModal(final ButtonInteractionEvent event) {
|
||||
String currentFormat = configRepo.get("counter.format");
|
||||
if (currentFormat == null) {
|
||||
currentFormat = "【👥】Участники: {count}";
|
||||
|
|
@ -288,7 +288,7 @@ public class SetupSlashHandler extends ListenerAdapter {
|
|||
event.replyModal(modal).queue();
|
||||
}
|
||||
|
||||
private void openLevelRoleAddModal(ButtonInteractionEvent event) {
|
||||
private void openLevelRoleAddModal(final ButtonInteractionEvent event) {
|
||||
TextInput levelInput = TextInput.create("level", TextInputStyle.SHORT)
|
||||
.setPlaceholder("10")
|
||||
.setRequired(true)
|
||||
|
|
@ -306,7 +306,7 @@ public class SetupSlashHandler extends ListenerAdapter {
|
|||
event.replyModal(modal).queue();
|
||||
}
|
||||
|
||||
private void openLevelRoleRemoveSelect(ButtonInteractionEvent event) {
|
||||
private void openLevelRoleRemoveSelect(final ButtonInteractionEvent event) {
|
||||
Map<String, String> allConfig = configRepo.getAll();
|
||||
var options = allConfig.entrySet().stream()
|
||||
.filter(e -> e.getKey().startsWith("level_role_"))
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ public class ConfigRepository implements StringConfigStore {
|
|||
|
||||
/** Получить значение конфигурации */
|
||||
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);
|
||||
ResultSet rs = stmt.executeQuery();
|
||||
|
||||
|
|
@ -36,8 +36,8 @@ public class ConfigRepository implements StringConfigStore {
|
|||
}
|
||||
|
||||
/** Установить значение конфигурации */
|
||||
public void set(String key, String value) {
|
||||
try (PreparedStatement stmt =
|
||||
public void set(String key, final String value) {
|
||||
try (final PreparedStatement stmt =
|
||||
database.prepare("INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)")) {
|
||||
stmt.setString(1, key);
|
||||
stmt.setString(2, value);
|
||||
|
|
@ -50,7 +50,7 @@ public class ConfigRepository implements StringConfigStore {
|
|||
|
||||
public Map<String, String> getAll() {
|
||||
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();
|
||||
while (rs.next()) {
|
||||
result.put(rs.getString("key"), rs.getString("value"));
|
||||
|
|
@ -63,7 +63,7 @@ public class ConfigRepository implements StringConfigStore {
|
|||
|
||||
/** Удалить значение конфигурации */
|
||||
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.executeUpdate();
|
||||
logger.info("Конфигурация удалена: {}", key);
|
||||
|
|
|
|||
|
|
@ -12,22 +12,22 @@ public final class PrefixedGuildConfigRepository implements GuildConfigRepositor
|
|||
this.store = store;
|
||||
}
|
||||
|
||||
private static String storageKey(String guildId, String key) {
|
||||
private static String storageKey(final String guildId, final String key) {
|
||||
return guildId + ":" + key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String get(String guildId, String key) {
|
||||
public String get(final String guildId, final String key) {
|
||||
return store.get(storageKey(guildId, key));
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String guildId, String key) {
|
||||
public void delete(final String guildId, final String key) {
|
||||
store.delete(storageKey(guildId, key));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,14 +15,13 @@ public class CounterModule extends AbstractModule {
|
|||
|
||||
@Provides
|
||||
@Singleton
|
||||
CounterStatsRepository provideCounterStatsRepository(Database database) {
|
||||
CounterStatsRepository provideCounterStatsRepository(final Database database) {
|
||||
return new CounterStatsRepository(database);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
CounterManager provideCounterManager(
|
||||
CounterStatsRepository statsRepo, ConfigRepository configRepo) {
|
||||
CounterManager provideCounterManager(final CounterStatsRepository statsRepo, final ConfigRepository configRepo) {
|
||||
return new CounterManager(statsRepo, configRepo);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,10 +25,10 @@ public class CounterStatsRepository {
|
|||
public DailyStats getStats(String 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);
|
||||
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
try (final ResultSet rs = stmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
DailyStats stats = new DailyStats();
|
||||
stats.setDate(rs.getString("date"));
|
||||
|
|
@ -70,7 +70,7 @@ public class CounterStatsRepository {
|
|||
difference = excluded.difference
|
||||
""";
|
||||
|
||||
try (PreparedStatement stmt = database.prepare(sql)) {
|
||||
try (final PreparedStatement stmt = database.prepare(sql)) {
|
||||
stmt.setString(1, stats.getDate());
|
||||
stmt.setInt(2, stats.getJoined());
|
||||
stmt.setInt(3, stats.getLeft());
|
||||
|
|
@ -82,14 +82,14 @@ public class CounterStatsRepository {
|
|||
}
|
||||
|
||||
/** Получить историю за последние N дней */
|
||||
public List<DailyStats> getHistory(int days) {
|
||||
public List<DailyStats> getHistory(final int days) {
|
||||
List<DailyStats> history = new ArrayList<>();
|
||||
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);
|
||||
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
try (final ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
DailyStats stats = new DailyStats();
|
||||
stats.setDate(rs.getString("date"));
|
||||
|
|
@ -107,14 +107,14 @@ public class CounterStatsRepository {
|
|||
}
|
||||
|
||||
/** Удалить старую статистику (старше N дней) */
|
||||
public void cleanOldStats(int daysToKeep) {
|
||||
public void cleanOldStats(final int daysToKeep) {
|
||||
String sql =
|
||||
"""
|
||||
DELETE FROM counter_stats
|
||||
WHERE date < date('now', '-' || ? || ' days')
|
||||
""";
|
||||
|
||||
try (PreparedStatement stmt = database.prepare(sql)) {
|
||||
try (final PreparedStatement stmt = database.prepare(sql)) {
|
||||
stmt.setInt(1, daysToKeep);
|
||||
int deleted = stmt.executeUpdate();
|
||||
if (deleted > 0) {
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ public class CounterManager {
|
|||
}
|
||||
|
||||
/** Обновить счетчик участников */
|
||||
public void updateCounter(Guild guild) {
|
||||
public void updateCounter(final Guild guild) {
|
||||
if (counterChannelId == null || counterChannelId.isEmpty()) {
|
||||
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);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ public class CounterSetupPrefixCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
if (!context.getAuthor().hasPermission(Permission.ADMINISTRATOR)) {
|
||||
context.getChannel().sendMessage("❌ У вас нет прав администратора!").queue();
|
||||
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) {
|
||||
context
|
||||
.getChannel()
|
||||
|
|
@ -98,7 +98,7 @@ public class CounterSetupPrefixCommand implements Command {
|
|||
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) {
|
||||
context
|
||||
.getChannel()
|
||||
|
|
@ -130,7 +130,7 @@ public class CounterSetupPrefixCommand implements Command {
|
|||
CounterConfigFormatter.sendFormatUpdated(format, context.getChannel());
|
||||
}
|
||||
|
||||
private void handleInfo(CommandContext context) {
|
||||
private void handleInfo(final CommandContext context) {
|
||||
String channelId = configRepo.get("counter.channel_id");
|
||||
String format = configRepo.get("counter.format");
|
||||
CounterConfigFormatter.sendInfo(context.getGuild(), channelId, format, context.getChannel());
|
||||
|
|
|
|||
|
|
@ -6,10 +6,7 @@ import creator.loki.embed.EmbedFactory;
|
|||
|
||||
public class CounterConfigFormatter {
|
||||
|
||||
public static void sendChannelSetConfirmation(
|
||||
net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel channel,
|
||||
int memberCount,
|
||||
net.dv8tion.jda.api.entities.channel.middleman.MessageChannel textChannel) {
|
||||
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) {
|
||||
textChannel
|
||||
.sendMessageEmbeds(
|
||||
EmbedFactory.create()
|
||||
|
|
@ -22,8 +19,7 @@ public class CounterConfigFormatter {
|
|||
.queue();
|
||||
}
|
||||
|
||||
public static void sendFormatUpdated(
|
||||
String format, net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel) {
|
||||
public static void sendFormatUpdated(final String format, final net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel) {
|
||||
channel
|
||||
.sendMessageEmbeds(
|
||||
EmbedFactory.create()
|
||||
|
|
@ -35,11 +31,7 @@ public class CounterConfigFormatter {
|
|||
.queue();
|
||||
}
|
||||
|
||||
public static void sendInfo(
|
||||
net.dv8tion.jda.api.entities.Guild guild,
|
||||
String channelId,
|
||||
String format,
|
||||
net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel) {
|
||||
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) {
|
||||
var embed =
|
||||
EmbedFactory.create()
|
||||
.withTitle("📊 Конфигурация счетчика участников")
|
||||
|
|
@ -59,8 +51,7 @@ public class CounterConfigFormatter {
|
|||
channel.sendMessageEmbeds(embed.build()).queue();
|
||||
}
|
||||
|
||||
public static void sendHelp(
|
||||
net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel) {
|
||||
public static void sendHelp(final net.dv8tion.jda.api.entities.channel.middleman.MessageChannel channel) {
|
||||
channel
|
||||
.sendMessageEmbeds(
|
||||
EmbedFactory.create()
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ public class MemberCounterListener extends ListenerAdapter implements Lifecycle
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
|
||||
public void onGuildMemberJoin(final GuildMemberJoinEvent event) {
|
||||
// Игнорируем ботов
|
||||
if (event.getUser().isBot()) {
|
||||
return;
|
||||
|
|
@ -64,7 +64,7 @@ public class MemberCounterListener extends ListenerAdapter implements Lifecycle
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onGuildMemberRemove(GuildMemberRemoveEvent event) {
|
||||
public void onGuildMemberRemove(final GuildMemberRemoveEvent event) {
|
||||
// Игнорируем ботов
|
||||
if (event.getUser().isBot()) {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ public class EconomyCommandRegistrar implements CommandRegistrar {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void register(CommandRegistry registry) {
|
||||
public void register(final CommandRegistry registry) {
|
||||
registry.register(new BalanceCommand(economyService));
|
||||
registry.register(new BaltopCommand(economyService));
|
||||
registry.register(new PayCommand(economyService));
|
||||
|
|
|
|||
|
|
@ -26,44 +26,43 @@ public class EconomyModule extends AbstractModule {
|
|||
|
||||
@Provides
|
||||
@Singleton
|
||||
EconomyRepository provideEconomyRepository(Database database) {
|
||||
EconomyRepository provideEconomyRepository(final Database database) {
|
||||
return new SqlEconomyRepository(database);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
EconomyService provideEconomyService(
|
||||
EconomyRepository repository, CooldownManager cooldownManager) {
|
||||
EconomyService provideEconomyService(final EconomyRepository repository, final CooldownManager cooldownManager) {
|
||||
return new EconomyService(repository, cooldownManager);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
FishingService provideFishingService(EconomyRepository repository) {
|
||||
FishingService provideFishingService(final EconomyRepository repository) {
|
||||
return new FishingService(repository);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
BlackjackService provideBlackjackService(EconomyRepository repository) {
|
||||
BlackjackService provideBlackjackService(final EconomyRepository repository) {
|
||||
return new BlackjackService(repository);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
SlotService provideSlotService(EconomyRepository repository) {
|
||||
SlotService provideSlotService(final EconomyRepository repository) {
|
||||
return new SlotService(repository);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
JobService provideJobService(EconomyRepository repository) {
|
||||
JobService provideJobService(final EconomyRepository repository) {
|
||||
return new JobService(repository);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
FishMessageListener provideFishMessageListener(FishingService fishingService) {
|
||||
FishMessageListener provideFishMessageListener(final FishingService fishingService) {
|
||||
return new FishMessageListener(fishingService);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ public class FishMessageListener extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onMessageReceived(@NotNull MessageReceivedEvent event) {
|
||||
public void onMessageReceived(@NotNull final MessageReceivedEvent event) {
|
||||
if (event.getAuthor().isBot()) return;
|
||||
|
||||
String content = event.getMessage().getContentRaw().trim();
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ public class BankCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext ctx) {
|
||||
public void execute(final CommandContext ctx) {
|
||||
List<String> args = ctx.getArgs();
|
||||
String uid = ctx.getAuthor().getId();
|
||||
if (args.isEmpty() || args.get(0).equalsIgnoreCase("balance")) {
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ public class BalanceCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
List<Member> mentioned = context.getMessage().getMentions().getMembers();
|
||||
Member target = mentioned.isEmpty() ? context.getAuthor() : mentioned.get(0);
|
||||
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ public class BaltopCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
List<EconomyAccount> top = economyService.getTopBalances(10);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ public class DailyCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
EconomyService.DailyResult result = economyService.claimDaily(context.getAuthor().getId());
|
||||
|
||||
if (result == null) {
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ public class PayCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
List<Member> mentioned = context.getMessage().getMentions().getMembers();
|
||||
if (mentioned.isEmpty()) {
|
||||
context
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ public class JobCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
var args = context.getArgs();
|
||||
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);
|
||||
if (current == null) {
|
||||
context
|
||||
|
|
@ -102,7 +102,7 @@ public class JobCommand implements Command {
|
|||
.queue();
|
||||
}
|
||||
|
||||
private void handleList(CommandContext context) {
|
||||
private void handleList(final CommandContext context) {
|
||||
var jobs = jobService.listJobs();
|
||||
var desc = new StringBuilder();
|
||||
|
||||
|
|
@ -131,7 +131,7 @@ public class JobCommand implements Command {
|
|||
.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();
|
||||
JobService.JobInfo target = null;
|
||||
|
||||
|
|
@ -168,7 +168,7 @@ public class JobCommand implements Command {
|
|||
.queue();
|
||||
}
|
||||
|
||||
private JobService.JobInfo findJob(String name) {
|
||||
private JobService.JobInfo findJob(final String name) {
|
||||
for (var job : jobService.listJobs()) {
|
||||
if (job.name().equalsIgnoreCase(name) || job.displayName().equalsIgnoreCase(name)) {
|
||||
return job;
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ public class WorkCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
var userId = context.getAuthor().getId();
|
||||
|
||||
String currentJob = jobService.getCurrentJob(userId);
|
||||
|
|
@ -77,7 +77,7 @@ public class WorkCommand implements Command {
|
|||
.queue();
|
||||
}
|
||||
|
||||
private JobService.JobInfo findJob(String name) {
|
||||
private JobService.JobInfo findJob(final String name) {
|
||||
for (var job : jobService.listJobs()) {
|
||||
if (job.name().equalsIgnoreCase(name) || job.displayName().equalsIgnoreCase(name)) {
|
||||
return job;
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ public class BlackjackCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
var args = context.getArgs();
|
||||
var userId = context.getAuthor().getId();
|
||||
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)) {
|
||||
context
|
||||
.getChannel()
|
||||
|
|
@ -110,7 +110,7 @@ public class BlackjackCommand implements Command {
|
|||
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)) {
|
||||
context
|
||||
.getChannel()
|
||||
|
|
@ -125,7 +125,7 @@ public class BlackjackCommand implements Command {
|
|||
context.getChannel().sendMessageEmbeds(buildGameEmbed(state)).queue();
|
||||
}
|
||||
|
||||
private MessageEmbed buildGameEmbed(BlackjackService.BlackjackState state) {
|
||||
private MessageEmbed buildGameEmbed(final BlackjackService.BlackjackState state) {
|
||||
var embed =
|
||||
EmbedFactory.create()
|
||||
.withTitle("🃏 Блэкджек")
|
||||
|
|
@ -143,17 +143,17 @@ public class BlackjackCommand implements Command {
|
|||
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;
|
||||
}
|
||||
|
||||
private String formatHiddenDealerCards(String[] cards) {
|
||||
private String formatHiddenDealerCards(final String[] cards) {
|
||||
var sb = new StringBuilder("?");
|
||||
for (int i = 1; i < cards.length; i++) sb.append(" + ").append(cards[i]);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String formatResult(BlackjackService.BlackjackState state) {
|
||||
private String formatResult(final BlackjackService.BlackjackState state) {
|
||||
long payout = state.payout();
|
||||
if (payout > state.bet()) return "🎉 Блэкджек! +" + payout + " LC";
|
||||
if (payout > 0) return "✅ Ты выиграл +" + payout + " LC";
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ public class FishCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
var args = context.getArgs();
|
||||
var userId = context.getAuthor().getId();
|
||||
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ public class SlotCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
var args = context.getArgs();
|
||||
var userId = context.getAuthor().getId();
|
||||
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ public class RobCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext ctx) {
|
||||
public void execute(final CommandContext ctx) {
|
||||
List<Member> mentioned = ctx.getMessage().getMentions().getMembers();
|
||||
if (mentioned.isEmpty()) {
|
||||
ctx.getChannel()
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ public class EconomyAccount {
|
|||
this.lastWork = null;
|
||||
}
|
||||
|
||||
EconomyAccount(EconomyAccountBuilder builder) {
|
||||
EconomyAccount(final EconomyAccountBuilder builder) {
|
||||
this.userId = builder.userId;
|
||||
this.cash = builder.cash;
|
||||
this.bank = builder.bank;
|
||||
|
|
@ -98,27 +98,27 @@ public class EconomyAccount {
|
|||
return cash + bank;
|
||||
}
|
||||
|
||||
public EconomyAccount withCash(long cash) {
|
||||
public EconomyAccount withCash(final long cash) {
|
||||
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();
|
||||
}
|
||||
|
||||
public EconomyAccount withAddedEarned(long amount) {
|
||||
public EconomyAccount withAddedEarned(final long amount) {
|
||||
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();
|
||||
}
|
||||
|
||||
public EconomyAccount withFishingLuck(int level) {
|
||||
public EconomyAccount withFishingLuck(final int level) {
|
||||
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();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ public class EconomyAccountBuilder {
|
|||
|
||||
public EconomyAccountBuilder() {}
|
||||
|
||||
public EconomyAccountBuilder(EconomyAccount existing) {
|
||||
public EconomyAccountBuilder(final EconomyAccount existing) {
|
||||
this.userId = existing.getUserId();
|
||||
this.cash = existing.getCash();
|
||||
this.bank = existing.getBank();
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ public enum Job {
|
|||
return emoji;
|
||||
}
|
||||
|
||||
public static Job fromName(String name) {
|
||||
public static Job fromName(final String name) {
|
||||
for (Job j : values()) {
|
||||
if (j.name().equalsIgnoreCase(name) || j.getDisplayName().equalsIgnoreCase(name)) {
|
||||
return j;
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ public enum SlotCombination {
|
|||
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;
|
||||
for (SlotCombination sc : values()) {
|
||||
if (sc.emojis[0].equals(e1)) return sc;
|
||||
|
|
|
|||
|
|
@ -6,15 +6,15 @@ import java.util.Optional;
|
|||
import creator.loki.feature.economy.domain.EconomyAccount;
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ public class SqlEconomyRepository implements EconomyRepository {
|
|||
+ "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 {
|
||||
if (value != null) {
|
||||
stmt.setString(index, value);
|
||||
|
|
@ -53,7 +53,7 @@ public class SqlEconomyRepository implements EconomyRepository {
|
|||
}
|
||||
|
||||
@Override
|
||||
public Optional<EconomyAccount> findById(String userId) {
|
||||
public Optional<EconomyAccount> findById(final String userId) {
|
||||
var sql = selectSql();
|
||||
try (var stmt = database.prepare(sql)) {
|
||||
stmt.setString(1, userId);
|
||||
|
|
@ -69,7 +69,7 @@ public class SqlEconomyRepository implements EconomyRepository {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void save(EconomyAccount account) {
|
||||
public void save(final EconomyAccount account) {
|
||||
var sql = upsertSql();
|
||||
try (var stmt = database.prepare(sql)) {
|
||||
stmt.setString(1, account.getUserId());
|
||||
|
|
@ -91,7 +91,7 @@ public class SqlEconomyRepository implements EconomyRepository {
|
|||
}
|
||||
|
||||
@Override
|
||||
public boolean exists(String userId) {
|
||||
public boolean exists(final String userId) {
|
||||
var sql = "SELECT 1 FROM economy WHERE user_id = ?";
|
||||
try (var stmt = database.prepare(sql)) {
|
||||
stmt.setString(1, userId);
|
||||
|
|
@ -105,7 +105,7 @@ public class SqlEconomyRepository implements EconomyRepository {
|
|||
}
|
||||
|
||||
@Override
|
||||
public List<EconomyAccount> findTopByBalance(int limit) {
|
||||
public List<EconomyAccount> findTopByBalance(final int limit) {
|
||||
var lim = clampLimit(limit);
|
||||
var sql =
|
||||
"SELECT "
|
||||
|
|
@ -125,12 +125,12 @@ public class SqlEconomyRepository implements EconomyRepository {
|
|||
return Collections.unmodifiableList(list);
|
||||
}
|
||||
|
||||
private static int clampLimit(int limit) {
|
||||
private static int clampLimit(final int limit) {
|
||||
if (limit <= 0) return 1;
|
||||
return Math.min(limit, MAX_TOP);
|
||||
}
|
||||
|
||||
private EconomyAccount mapResultSetToAccount(ResultSet rs) throws SQLException {
|
||||
private EconomyAccount mapResultSetToAccount(final ResultSet rs) throws SQLException {
|
||||
return new EconomyAccountBuilder()
|
||||
.userId(rs.getString("user_id"))
|
||||
.cash(rs.getLong("cash"))
|
||||
|
|
|
|||
|
|
@ -22,11 +22,11 @@ public class EconomyService {
|
|||
this.cooldownManager = cooldownManager;
|
||||
}
|
||||
|
||||
public EconomyAccount getAccount(String userId) {
|
||||
public EconomyAccount getAccount(final String 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;
|
||||
EconomyAccount from = repository.getAccount(fromId);
|
||||
if (from.getCash() < amount) return false;
|
||||
|
|
@ -36,7 +36,7 @@ public class EconomyService {
|
|||
return true;
|
||||
}
|
||||
|
||||
public boolean deposit(String userId, long amount) {
|
||||
public boolean deposit(final String userId, long amount) {
|
||||
if (amount <= 0) return false;
|
||||
EconomyAccount account = repository.getAccount(userId);
|
||||
if (account.getCash() < amount) return false;
|
||||
|
|
@ -45,7 +45,7 @@ public class EconomyService {
|
|||
return true;
|
||||
}
|
||||
|
||||
public boolean withdraw(String userId, long amount) {
|
||||
public boolean withdraw(final String userId, long amount) {
|
||||
if (amount <= 0) return false;
|
||||
EconomyAccount account = repository.getAccount(userId);
|
||||
if (account.getBank() < amount) return false;
|
||||
|
|
@ -54,14 +54,14 @@ public class EconomyService {
|
|||
return true;
|
||||
}
|
||||
|
||||
public long earnCash(String userId, long amount) {
|
||||
public long earnCash(final String userId, long amount) {
|
||||
EconomyAccount account = repository.getAccount(userId);
|
||||
EconomyAccount updated = account.withCash(account.getCash() + amount).withAddedEarned(amount);
|
||||
repository.save(updated);
|
||||
return updated.getCash();
|
||||
}
|
||||
|
||||
public boolean spendCash(String userId, long amount) {
|
||||
public boolean spendCash(final String userId, long amount) {
|
||||
if (amount <= 0) return false;
|
||||
EconomyAccount account = repository.getAccount(userId);
|
||||
if (account.getCash() < amount) return false;
|
||||
|
|
@ -69,7 +69,7 @@ public class EconomyService {
|
|||
return true;
|
||||
}
|
||||
|
||||
public DailyResult claimDaily(String userId) {
|
||||
public DailyResult claimDaily(final String userId) {
|
||||
EconomyAccount account = repository.getAccount(userId);
|
||||
String today = LocalDate.now().toString();
|
||||
if (today.equals(account.getLastDaily())) return null;
|
||||
|
|
@ -93,7 +93,7 @@ public class EconomyService {
|
|||
return new DailyResult(amount, streak, newCash);
|
||||
}
|
||||
|
||||
public int upgradeFishingLuck(String userId) {
|
||||
public int upgradeFishingLuck(final String userId) {
|
||||
EconomyAccount account = repository.getAccount(userId);
|
||||
if (account.getFishingLuck() >= 5) return -1;
|
||||
long cost = 800L * (account.getFishingLuck() + 1);
|
||||
|
|
@ -104,7 +104,7 @@ public class EconomyService {
|
|||
return newLevel;
|
||||
}
|
||||
|
||||
public int upgradeEfficiency(String userId) {
|
||||
public int upgradeEfficiency(final String userId) {
|
||||
EconomyAccount account = repository.getAccount(userId);
|
||||
if (account.getEfficiency() >= 5) return -1;
|
||||
long cost = 800L * (account.getEfficiency() + 1);
|
||||
|
|
@ -115,7 +115,7 @@ public class EconomyService {
|
|||
return newLevel;
|
||||
}
|
||||
|
||||
public List<EconomyAccount> getTopBalances(int limit) {
|
||||
public List<EconomyAccount> getTopBalances(final int limit) {
|
||||
return repository.findTopByBalance(limit);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ public class FishingService {
|
|||
private record ActiveFish(
|
||||
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);
|
||||
if (account.getLastFish() != null) {
|
||||
long elapsed = System.currentTimeMillis() - Long.parseLong(account.getLastFish());
|
||||
|
|
@ -98,13 +98,13 @@ public class FishingService {
|
|||
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);
|
||||
if (session == null) return null;
|
||||
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);
|
||||
if (session == null) return null;
|
||||
if (session.startTime() != startTime || !session.difficulty().equals(difficulty)) return null;
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ public class BlackjackService {
|
|||
private record ActiveBlackjack(
|
||||
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;
|
||||
var account = repository.getAccount(userId);
|
||||
if (account.getCash() < bet) return null;
|
||||
|
|
@ -52,7 +52,7 @@ public class BlackjackService {
|
|||
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);
|
||||
if (game == null) return null;
|
||||
|
||||
|
|
@ -72,7 +72,7 @@ public class BlackjackService {
|
|||
0);
|
||||
}
|
||||
|
||||
public BlackjackState stand(String userId) {
|
||||
public BlackjackState stand(final String userId) {
|
||||
var game = activeGames.remove(userId);
|
||||
if (game == null) return null;
|
||||
|
||||
|
|
@ -91,7 +91,7 @@ public class BlackjackService {
|
|||
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;
|
||||
var account = repository.getAccount(userId);
|
||||
repository.save(account.withCash(account.getCash() + amount));
|
||||
|
|
@ -101,7 +101,7 @@ public class BlackjackService {
|
|||
return DECK[ThreadLocalRandom.current().nextInt(DECK.length)];
|
||||
}
|
||||
|
||||
private int calculateSum(List<String> cards) {
|
||||
private int calculateSum(final List<String> cards) {
|
||||
var sum = 0;
|
||||
var aces = 0;
|
||||
for (var c : cards) {
|
||||
|
|
@ -121,14 +121,7 @@ public class BlackjackService {
|
|||
return sum;
|
||||
}
|
||||
|
||||
private BlackjackState buildState(
|
||||
List<String> playerCards,
|
||||
List<String> dealerCards,
|
||||
int playerSum,
|
||||
int dealerSum,
|
||||
long bet,
|
||||
boolean isOver,
|
||||
long payout) {
|
||||
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) {
|
||||
return new BlackjackState(
|
||||
playerCards.toArray(String[]::new),
|
||||
dealerCards.toArray(String[]::new),
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ public class JobService {
|
|||
this.repository = repository;
|
||||
}
|
||||
|
||||
public void setJob(String userId, String jobName) {
|
||||
public void setJob(final String userId, String jobName) {
|
||||
Job job = Job.fromName(jobName);
|
||||
if (job == null) return;
|
||||
EconomyAccount account = repository.getAccount(userId);
|
||||
|
|
@ -31,7 +31,7 @@ public class JobService {
|
|||
repository.save(updated);
|
||||
}
|
||||
|
||||
public WorkResult work(String userId, int userLevel) {
|
||||
public WorkResult work(final String userId, final int userLevel) {
|
||||
EconomyAccount account = repository.getAccount(userId);
|
||||
String jobName = account.getJob();
|
||||
if (jobName == null) return null;
|
||||
|
|
@ -76,7 +76,7 @@ public class JobService {
|
|||
return infos;
|
||||
}
|
||||
|
||||
public String getCurrentJob(String userId) {
|
||||
public String getCurrentJob(final String userId) {
|
||||
EconomyAccount account = repository.getAccount(userId);
|
||||
String jobName = account.getJob();
|
||||
if (jobName == null) return null;
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ public class SlotService {
|
|||
this.repository = repository;
|
||||
}
|
||||
|
||||
public SlotResult spin(String userId, long bet) {
|
||||
public SlotResult spin(final String userId, final long bet) {
|
||||
if (bet <= 0) return null;
|
||||
EconomyAccount account = repository.getAccount(userId);
|
||||
if (account.getCash() < bet) return null;
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ public class EntertainmentCommandRegistrar implements CommandRegistrar {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void register(CommandRegistry registry) {
|
||||
public void register(final CommandRegistry registry) {
|
||||
registry.register(new EightBallCommand());
|
||||
registry.register(new CoinCommand());
|
||||
registry.register(new DiceCommand());
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ public class GlazbobaCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
List<Member> mentioned = context.getMessage().getMentions().getMembers();
|
||||
if (mentioned.isEmpty()) {
|
||||
context.getChannel().sendMessage("Укажи пользователя через @").queue();
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ public class MemeCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
context
|
||||
.getChannel()
|
||||
.sendMessage("🔍 Ищу мем...")
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ public class RandomChoiceCommand implements Command {
|
|||
this.templates = templates;
|
||||
}
|
||||
|
||||
String randomLine(String pick) {
|
||||
String randomLine(final String pick) {
|
||||
var rnd = ThreadLocalRandom.current();
|
||||
return String.format(templates[rnd.nextInt(templates.length)], pick);
|
||||
}
|
||||
|
|
@ -88,7 +88,7 @@ public class RandomChoiceCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
String p = config.getPrefix();
|
||||
String tail =
|
||||
ChoiceOptionParser.tailAfterCommand(context.getMessage().getContentRaw(), p, commandName);
|
||||
|
|
@ -123,11 +123,11 @@ public class RandomChoiceCommand implements Command {
|
|||
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();
|
||||
}
|
||||
|
||||
private String usageExamples(String p) {
|
||||
private String usageExamples(final String p) {
|
||||
return "**Примеры:**\n"
|
||||
+ "`"
|
||||
+ p
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ public class CoinCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
boolean isHeads = random.nextBoolean();
|
||||
String result = isHeads ? "Орёл" : "Решка";
|
||||
String emoji = isHeads ? "🦅" : "🪙";
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ public class DiceCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
int maxValue = 6;
|
||||
|
||||
if (!context.getArgs().isEmpty()) {
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ public class EightBallCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
if (context.getArgs().isEmpty()) {
|
||||
context.getChannel().sendMessage("Задай вопрос!").queue();
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -22,18 +22,18 @@ public class RatingService {
|
|||
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;
|
||||
RANDOM.setSeed(seed);
|
||||
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();
|
||||
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)) {
|
||||
long remaining =
|
||||
cooldownManager.getRemainingSeconds(context.getAuthor().getId(), commandName);
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ public class HelpMenuHandler extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onStringSelectInteraction(StringSelectInteractionEvent event) {
|
||||
public void onStringSelectInteraction(final StringSelectInteractionEvent event) {
|
||||
if (!event.getComponentId().equals("help:category")) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -100,8 +100,7 @@ public class HelpMenuHandler extends ListenerAdapter {
|
|||
event.editMessageEmbeds(embed.build()).setComponents(ActionRow.of(menuBuilder.build())).queue();
|
||||
}
|
||||
|
||||
private EmbedFactory createCategoryEmbed(
|
||||
String category, List<Command> commands, StringSelectInteractionEvent event) {
|
||||
private EmbedFactory createCategoryEmbed(final String category, final List<Command> commands, final StringSelectInteractionEvent event) {
|
||||
String emoji = HelpCategories.getEmoji(category);
|
||||
Color color = HelpCategories.getColor(category);
|
||||
|
||||
|
|
@ -153,7 +152,7 @@ public class HelpMenuHandler extends ListenerAdapter {
|
|||
return embed;
|
||||
}
|
||||
|
||||
private static boolean isNsfw(StringSelectInteractionEvent event) {
|
||||
private static boolean isNsfw(final StringSelectInteractionEvent event) {
|
||||
return event.getChannel() instanceof IAgeRestrictedChannel arc && arc.isNSFW();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ public class HelpCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
var commands = registry.getAllCommands();
|
||||
Map<String, List<Command>> commandsByCategory =
|
||||
commands.stream().collect(Collectors.groupingBy(Command::getCategory));
|
||||
|
|
@ -86,16 +86,11 @@ public class HelpCommand implements Command {
|
|||
.queue();
|
||||
}
|
||||
|
||||
private static boolean isNsfw(CommandContext context) {
|
||||
private static boolean isNsfw(final CommandContext context) {
|
||||
return context.getChannel() instanceof IAgeRestrictedChannel arc && arc.isNSFW();
|
||||
}
|
||||
|
||||
private EmbedFactory createMainPage(
|
||||
CommandContext context,
|
||||
Map<String, List<Command>> commandsByCategory,
|
||||
boolean isAdmin,
|
||||
boolean isSuper,
|
||||
boolean isNsfwChannel) {
|
||||
private EmbedFactory createMainPage(final CommandContext context, final Map<String, List<Command>> commandsByCategory, final boolean isAdmin, final boolean isSuper, final boolean isNsfwChannel) {
|
||||
int totalCommands =
|
||||
commandsByCategory.entrySet().stream()
|
||||
.filter(
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ public class ImageModule extends AbstractModule {
|
|||
|
||||
@Provides
|
||||
@Singleton
|
||||
ImageService provideImageService(BotConfig config) {
|
||||
ImageService provideImageService(final BotConfig config) {
|
||||
return new ImageService(config);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ public abstract class AbstractImageCommand implements Command {
|
|||
// ── Общая логика execute ─────────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
if (!isNsfwChannel(context)) {
|
||||
context
|
||||
.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, "");
|
||||
try {
|
||||
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();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import creator.loki.feature.image.commands.AbstractImageCommand;
|
|||
|
||||
public class GelbooruCommand extends AbstractImageCommand {
|
||||
|
||||
public GelbooruCommand(ImageService imageService, ImageSessionManager sessionManager) {
|
||||
public GelbooruCommand(final ImageService imageService, final ImageSessionManager sessionManager) {
|
||||
super(imageService, sessionManager);
|
||||
}
|
||||
|
||||
|
|
@ -50,7 +50,7 @@ public class GelbooruCommand extends AbstractImageCommand {
|
|||
}
|
||||
|
||||
@Override
|
||||
protected List<String> fetchUrls(String tags, int limit) {
|
||||
protected List<String> fetchUrls(final String tags, final int limit) {
|
||||
return imageService.fetchGelbooru(tags, limit);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import creator.loki.feature.image.commands.AbstractImageCommand;
|
|||
|
||||
public class YandereCommand extends AbstractImageCommand {
|
||||
|
||||
public YandereCommand(ImageService imageService, ImageSessionManager sessionManager) {
|
||||
public YandereCommand(final ImageService imageService, final ImageSessionManager sessionManager) {
|
||||
super(imageService, sessionManager);
|
||||
}
|
||||
|
||||
|
|
@ -50,7 +50,7 @@ public class YandereCommand extends AbstractImageCommand {
|
|||
}
|
||||
|
||||
@Override
|
||||
protected List<String> fetchUrls(String tags, int limit) {
|
||||
protected List<String> fetchUrls(final String tags, final int limit) {
|
||||
return imageService.fetchYandere(tags, limit);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import creator.loki.feature.image.commands.AbstractImageCommand;
|
|||
|
||||
public class E621Command extends AbstractImageCommand {
|
||||
|
||||
public E621Command(ImageService imageService, ImageSessionManager sessionManager) {
|
||||
public E621Command(final ImageService imageService, final ImageSessionManager sessionManager) {
|
||||
super(imageService, sessionManager);
|
||||
}
|
||||
|
||||
|
|
@ -50,7 +50,7 @@ public class E621Command extends AbstractImageCommand {
|
|||
}
|
||||
|
||||
@Override
|
||||
protected List<String> fetchUrls(String tags, int limit) {
|
||||
protected List<String> fetchUrls(final String tags, final int limit) {
|
||||
return imageService.fetchE621(tags, limit);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import creator.loki.feature.image.commands.AbstractImageCommand;
|
|||
|
||||
public class E621RandomCommand extends AbstractImageCommand {
|
||||
|
||||
public E621RandomCommand(ImageService imageService, ImageSessionManager sessionManager) {
|
||||
public E621RandomCommand(final ImageService imageService, final ImageSessionManager sessionManager) {
|
||||
super(imageService, sessionManager);
|
||||
}
|
||||
|
||||
|
|
@ -54,13 +54,13 @@ public class E621RandomCommand extends AbstractImageCommand {
|
|||
}
|
||||
|
||||
@Override
|
||||
protected List<String> fetchUrls(String tags, int limit) {
|
||||
protected List<String> fetchUrls(final String tags, int limit) {
|
||||
return imageService.fetchE621("", limit); // теги игнорируются — всегда случайные
|
||||
}
|
||||
|
||||
/** Переопределяем execute: теги не нужны, лимит берём из первого аргумента. */
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
if (!isNsfwChannel(context)) {
|
||||
context
|
||||
.getChannel()
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ public class ImageNavigationHandler extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onButtonInteraction(ButtonInteractionEvent event) {
|
||||
public void onButtonInteraction(final ButtonInteractionEvent event) {
|
||||
String id = event.getComponentId();
|
||||
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()) {
|
||||
// Есть готовая следующая страница в кеше
|
||||
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;
|
||||
logger.debug("nav: prev page={}/{}", session.page() - 1, session.totalPages());
|
||||
ImageSession updated = session.withPage(session.page() - 1);
|
||||
|
|
@ -86,7 +86,7 @@ public class ImageNavigationHandler extends ListenerAdapter {
|
|||
|
||||
// ── Подгрузка с 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;
|
||||
logger.debug(
|
||||
"loadMore: site={} tags='{}' apiPage={}", session.site(), session.tags(), nextApiPage);
|
||||
|
|
@ -105,7 +105,7 @@ public class ImageNavigationHandler extends ListenerAdapter {
|
|||
.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) {
|
||||
case "e621.net" -> imageService.fetchE621(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
|
||||
.editMessageEmbeds(ImageEmbedHelper.buildEmbeds(session))
|
||||
.setComponents(ImageEmbedHelper.buildActionRow(session))
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ public class ImageService {
|
|||
private final OkHttpClient client;
|
||||
|
||||
@Inject
|
||||
public ImageService(BotConfig config) {
|
||||
public ImageService(final BotConfig config) {
|
||||
this.client =
|
||||
new OkHttpClient.Builder()
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
|
|
@ -44,7 +44,7 @@ public class ImageService {
|
|||
Request request =
|
||||
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) {
|
||||
logger.error("e621 API error: {} {}", response.code(), response.message());
|
||||
return List.of();
|
||||
|
|
@ -107,11 +107,11 @@ public class ImageService {
|
|||
return fetchBooruJson(url, limit);
|
||||
}
|
||||
|
||||
private List<String> fetchBooruJson(String url, int limit) {
|
||||
private List<String> fetchBooruJson(final String url, final int limit) {
|
||||
Request request =
|
||||
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) {
|
||||
logger.error("Booru API error: {} {}", response.code(), response.message());
|
||||
return List.of();
|
||||
|
|
|
|||
|
|
@ -28,14 +28,7 @@ public record ImageSession(
|
|||
|
||||
// ── Фабричный метод ──────────────────────────────────────────────────────────
|
||||
|
||||
public static ImageSession create(
|
||||
List<String> urls,
|
||||
int pageSize,
|
||||
String site,
|
||||
java.awt.Color color,
|
||||
String tags,
|
||||
long userId,
|
||||
long guildId) {
|
||||
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) {
|
||||
return new ImageSession(
|
||||
urls,
|
||||
0,
|
||||
|
|
@ -73,7 +66,7 @@ public record ImageSession(
|
|||
|
||||
// ── Мутации (возвращают новый экземпляр) ────────────────────────────────────
|
||||
|
||||
public ImageSession withPage(int newPage) {
|
||||
public ImageSession withPage(final int newPage) {
|
||||
return new ImageSession(
|
||||
urls,
|
||||
newPage,
|
||||
|
|
@ -92,7 +85,7 @@ public record ImageSession(
|
|||
* Добавляем новые URL из следующей API-страницы и переходим на следующую внутреннюю страницу.
|
||||
* Если newUrls пустой — помечаем сессию как exhausted.
|
||||
*/
|
||||
public ImageSession withMoreUrls(List<String> newUrls) {
|
||||
public ImageSession withMoreUrls(final List<String> newUrls) {
|
||||
if (newUrls.isEmpty()) {
|
||||
// API больше ничего не отдал — остаёмся на месте, ставим флаг
|
||||
return new ImageSession(
|
||||
|
|
|
|||
|
|
@ -11,12 +11,12 @@ public class ImageSessionManager {
|
|||
private static final long SESSION_TTL = 5 * 60 * 1000;
|
||||
private final Map<String, ImageSession> sessions = new ConcurrentHashMap<>();
|
||||
|
||||
public void put(String messageId, ImageSession session) {
|
||||
public void put(final String messageId, ImageSession session) {
|
||||
cleanup();
|
||||
sessions.put(messageId, session);
|
||||
}
|
||||
|
||||
public ImageSession get(String messageId) {
|
||||
public ImageSession get(final String messageId) {
|
||||
ImageSession session = sessions.get(messageId);
|
||||
if (session == null) return null;
|
||||
if (System.currentTimeMillis() - session.createdAt() > SESSION_TTL) {
|
||||
|
|
@ -26,11 +26,11 @@ public class ImageSessionManager {
|
|||
return session;
|
||||
}
|
||||
|
||||
public void update(String messageId, ImageSession session) {
|
||||
public void update(final String messageId, final ImageSession session) {
|
||||
sessions.put(messageId, session);
|
||||
}
|
||||
|
||||
public void remove(String messageId) {
|
||||
public void remove(final String messageId) {
|
||||
sessions.remove(messageId);
|
||||
}
|
||||
|
||||
|
|
@ -39,7 +39,7 @@ public class ImageSessionManager {
|
|||
sessions.values().removeIf(s -> now - s.createdAt() > SESSION_TTL);
|
||||
}
|
||||
|
||||
public static Color parseColor(String hex) {
|
||||
public static Color parseColor(final String hex) {
|
||||
try {
|
||||
return Color.decode(hex);
|
||||
} catch (NumberFormatException e) {
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ public class ImageCommandRegistrar implements CommandRegistrar {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void register(CommandRegistry registry) {
|
||||
public void register(final CommandRegistry registry) {
|
||||
registry.register(new E621Command(imageService, sessionManager));
|
||||
registry.register(new E621RandomCommand(imageService, sessionManager));
|
||||
registry.register(new GelbooruCommand(imageService, sessionManager));
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ public final class ImageEmbedHelper {
|
|||
|
||||
private ImageEmbedHelper() {}
|
||||
|
||||
public static MessageEmbed[] buildEmbeds(ImageSession session) {
|
||||
public static MessageEmbed[] buildEmbeds(final ImageSession session) {
|
||||
String tagsStr = formatTags(session.tags());
|
||||
List<MessageEmbed> embeds = new ArrayList<>();
|
||||
List<String> pageUrls = session.currentPageUrls();
|
||||
|
|
@ -84,7 +84,7 @@ public final class ImageEmbedHelper {
|
|||
return embeds.toArray(new MessageEmbed[0]);
|
||||
}
|
||||
|
||||
public static ActionRow buildActionRow(ImageSession session) {
|
||||
public static ActionRow buildActionRow(final ImageSession session) {
|
||||
boolean noPrev = !session.hasPrev();
|
||||
boolean noNext = !session.hasNext() && session.exhausted();
|
||||
return ActionRow.of(
|
||||
|
|
@ -111,7 +111,7 @@ public final class ImageEmbedHelper {
|
|||
return (tags == null || tags.isBlank()) ? "" : " `" + tags + "`";
|
||||
}
|
||||
|
||||
private static String extension(String url) {
|
||||
private static String extension(final String url) {
|
||||
int dot = url.lastIndexOf('.');
|
||||
if (dot < 0 || dot >= url.length() - 1) return "";
|
||||
int end = url.indexOf('?', dot);
|
||||
|
|
@ -119,7 +119,7 @@ public final class ImageEmbedHelper {
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ public class AvatarCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
User targetUser;
|
||||
|
||||
// Если упомянут пользователь - показываем его аватар
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ public class InfoCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
String type = context.getArgs().isEmpty() ? "server" : context.getArgs().get(0).toLowerCase();
|
||||
|
||||
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();
|
||||
if (guild == null) return;
|
||||
|
||||
|
|
@ -78,7 +78,7 @@ public class InfoCommand implements Command {
|
|||
.queue();
|
||||
}
|
||||
|
||||
private void showUserInfo(CommandContext context) {
|
||||
private void showUserInfo(final CommandContext context) {
|
||||
Member member = context.getAuthor();
|
||||
if (member == null) return;
|
||||
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ public class PingCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
context
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ public class ServerStatsCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
Guild guild = context.getGuild();
|
||||
if (guild == null) {
|
||||
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
|
||||
.loadMembers()
|
||||
.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
|
||||
.getChannel()
|
||||
.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
|
||||
.getChannel()
|
||||
.sendMessage("⏳ Генерирую график...")
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ public class LeaderboardButtonListener extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onButtonInteraction(ButtonInteractionEvent event) {
|
||||
public void onButtonInteraction(final ButtonInteractionEvent event) {
|
||||
String buttonId = event.getComponentId();
|
||||
|
||||
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 embed = LeaderboardFormatter.formatLevelLeaderboard(top);
|
||||
event.getHook().editOriginalEmbeds(embed).queue();
|
||||
}
|
||||
|
||||
private void showMessageLeaderboard(ButtonInteractionEvent event) {
|
||||
private void showMessageLeaderboard(final ButtonInteractionEvent event) {
|
||||
var top = leaderboardService.getTopByMessages(10);
|
||||
var embed = LeaderboardFormatter.formatMessageLeaderboard(top);
|
||||
event.getHook().editOriginalEmbeds(embed).queue();
|
||||
}
|
||||
|
||||
private void showVoiceLeaderboard(ButtonInteractionEvent event) {
|
||||
private void showVoiceLeaderboard(final ButtonInteractionEvent event) {
|
||||
var top = leaderboardService.getTopByVoice(10);
|
||||
var embed = LeaderboardFormatter.formatVoiceLeaderboard(top);
|
||||
event.getHook().editOriginalEmbeds(embed).queue();
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ public class LeaderboardCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
var top = leaderboardService.getTopByLevel(10);
|
||||
|
||||
if (top.isEmpty()) {
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import net.dv8tion.jda.api.entities.MessageEmbed;
|
|||
/** Форматирование таблиц лидеров (DRY принцип) */
|
||||
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(
|
||||
top,
|
||||
"🏆 Топ-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(
|
||||
top,
|
||||
"💬 Топ-10 по сообщениям",
|
||||
|
|
@ -31,7 +31,7 @@ public class LeaderboardFormatter {
|
|||
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(
|
||||
top,
|
||||
"🎤 Топ-10 по времени в войсе",
|
||||
|
|
@ -44,11 +44,7 @@ public class LeaderboardFormatter {
|
|||
});
|
||||
}
|
||||
|
||||
private static MessageEmbed formatLeaderboard(
|
||||
List<Map.Entry<String, UserStats>> top,
|
||||
String title,
|
||||
Color color,
|
||||
Function<Map.Entry<String, UserStats>, String> statFormatter) {
|
||||
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) {
|
||||
StringBuilder description = new StringBuilder();
|
||||
int position = 1;
|
||||
|
||||
|
|
@ -79,7 +75,7 @@ public class LeaderboardFormatter {
|
|||
.build();
|
||||
}
|
||||
|
||||
private static String getPositionEmoji(int position) {
|
||||
private static String getPositionEmoji(final int position) {
|
||||
return switch (position) {
|
||||
case 1 -> "🥇";
|
||||
case 2 -> "🥈";
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ public class LevelModule extends AbstractModule {
|
|||
|
||||
@Provides
|
||||
@Singleton
|
||||
UserStatsRepository provideUserStatsRepository(Database database) {
|
||||
UserStatsRepository provideUserStatsRepository(final Database database) {
|
||||
return new SqlUserStatsRepository(database);
|
||||
}
|
||||
|
||||
|
|
@ -47,40 +47,37 @@ public class LevelModule extends AbstractModule {
|
|||
|
||||
@Provides
|
||||
@Singleton
|
||||
MessageCooldownService provideMessageCooldownService(UserStatsRepository repository) {
|
||||
MessageCooldownService provideMessageCooldownService(final UserStatsRepository repository) {
|
||||
return new MessageCooldownService(repository);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
LeaderboardService provideLeaderboardService(UserStatsRepository repository) {
|
||||
LeaderboardService provideLeaderboardService(final UserStatsRepository repository) {
|
||||
return new LeaderboardService(repository);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
LevelService provideLevelService(
|
||||
UserStatsRepository repository, XpFormula xpFormula, MessageCooldownService cooldownService) {
|
||||
LevelService provideLevelService(final UserStatsRepository repository, final XpFormula xpFormula, final MessageCooldownService cooldownService) {
|
||||
return new LevelService(repository, xpFormula, cooldownService);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
LevelRoleService provideLevelRoleService(ConfigRepository configRepository) {
|
||||
LevelRoleService provideLevelRoleService(final ConfigRepository configRepository) {
|
||||
return new LevelRoleService(configRepository);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
LevelUpNotifier provideLevelUpNotifier(
|
||||
ConfigRepository configRepo, LevelService levelService, LevelRoleService levelRoleService) {
|
||||
LevelUpNotifier provideLevelUpNotifier(final ConfigRepository configRepo, final LevelService levelService, final LevelRoleService levelRoleService) {
|
||||
return new LevelUpNotifier(configRepo, levelService, levelRoleService);
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
ResetLevelsCommand provideResetLevelsCommand(
|
||||
UserStatsRepository userStatsRepository, GuildConfigRepository guildConfigRepository) {
|
||||
ResetLevelsCommand provideResetLevelsCommand(final UserStatsRepository userStatsRepository, final GuildConfigRepository guildConfigRepository) {
|
||||
return new ResetLevelsCommand(userStatsRepository, guildConfigRepository);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ public class LevelCommandRegistrar implements CommandRegistrar {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void register(CommandRegistry registry) {
|
||||
public void register(final CommandRegistry registry) {
|
||||
registry.register(new LeaderboardCommand(leaderboardService));
|
||||
registry.register(new StatsCommand());
|
||||
registry.register(resetLevelsCommand);
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ public class LevelRoleCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
if (context.getAuthor() == null
|
||||
|| !context.getAuthor().hasPermission(Permission.ADMINISTRATOR)) {
|
||||
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) {
|
||||
context
|
||||
.getChannel()
|
||||
|
|
@ -127,7 +127,7 @@ public class LevelRoleCommand implements Command {
|
|||
.queue();
|
||||
}
|
||||
|
||||
private void handleRemove(CommandContext context, List<String> args) {
|
||||
private void handleRemove(final CommandContext context, final List<String> args) {
|
||||
if (args.size() < 2) {
|
||||
context
|
||||
.getChannel()
|
||||
|
|
@ -158,7 +158,7 @@ public class LevelRoleCommand implements Command {
|
|||
.queue();
|
||||
}
|
||||
|
||||
private void handleClear(CommandContext context) {
|
||||
private void handleClear(final CommandContext context) {
|
||||
Map<String, String> allConfig = configRepository.getAll();
|
||||
int removed = 0;
|
||||
for (String key : allConfig.keySet()) {
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@ public class ResetLevelsCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
// Проверка прав администратора
|
||||
if (context.getAuthor() == null
|
||||
|| !context.getAuthor().hasPermission(Permission.ADMINISTRATOR)) {
|
||||
|
|
@ -127,7 +127,7 @@ public class ResetLevelsCommand implements Command {
|
|||
}
|
||||
|
||||
/** Выполняет сброс уровней (вызывается из ButtonHandler) */
|
||||
public void executeReset(String guildId, String userId) {
|
||||
public void executeReset(final String guildId, final String userId) {
|
||||
try {
|
||||
LoggerDecorator.warn(logger, "Начало сброса уровней для гильдии: " + guildId);
|
||||
LoggerDecorator.warn(logger, "Инициатор: " + userId);
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ public class StatsCommand implements Command {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void execute(CommandContext context) {
|
||||
public void execute(final CommandContext context) {
|
||||
if (context.getGuild() == null) {
|
||||
context.getChannel().sendMessage("Команда доступна только на сервере").queue();
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -9,8 +9,7 @@ import net.dv8tion.jda.api.EmbedBuilder;
|
|||
|
||||
public class LevelRoleFormatter {
|
||||
|
||||
public static EmbedBuilder buildMappingsEmbed(
|
||||
ConfigRepository configRepository, LevelRoleService levelRoleService) {
|
||||
public static EmbedBuilder buildMappingsEmbed(final ConfigRepository configRepository, final LevelRoleService levelRoleService) {
|
||||
Map<String, String> allConfig = configRepository.getAll();
|
||||
Map<Integer, String> customRoles =
|
||||
allConfig.entrySet().stream()
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ public class UserStats {
|
|||
this.lastVoiceJoin = 0;
|
||||
}
|
||||
|
||||
private UserStats(Builder builder) {
|
||||
private UserStats(final Builder builder) {
|
||||
this.userId = builder.userId;
|
||||
this.level = builder.level;
|
||||
this.totalXP = builder.totalXP;
|
||||
|
|
@ -63,15 +63,15 @@ public class UserStats {
|
|||
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();
|
||||
}
|
||||
|
||||
public UserStats withRecordedMessage(long timestamp) {
|
||||
public UserStats withRecordedMessage(final long timestamp) {
|
||||
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();
|
||||
}
|
||||
|
||||
|
|
@ -106,7 +106,7 @@ public class UserStats {
|
|||
|
||||
public Builder() {}
|
||||
|
||||
public Builder(UserStats existing) {
|
||||
public Builder(final UserStats existing) {
|
||||
this.userId = existing.userId;
|
||||
this.level = existing.level;
|
||||
this.totalXP = existing.totalXP;
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ public class XpFormula {
|
|||
* @param level целевой уровень
|
||||
* @return общее количество XP
|
||||
*/
|
||||
public int getTotalXPForLevel(int level) {
|
||||
public int getTotalXPForLevel(final int level) {
|
||||
if (level <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -23,7 +23,7 @@ public class XpFormula {
|
|||
* @param xp текущее количество XP
|
||||
* @return текущий уровень
|
||||
*/
|
||||
public int calculateLevel(int xp) {
|
||||
public int calculateLevel(final int xp) {
|
||||
if (xp <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -37,7 +37,7 @@ public class XpFormula {
|
|||
* @param currentLevel текущий уровень
|
||||
* @return XP для следующего уровня
|
||||
*/
|
||||
public int getXpForNextLevel(int currentLevel) {
|
||||
public int getXpForNextLevel(final int currentLevel) {
|
||||
return XP_PER_LEVEL * (currentLevel + 1);
|
||||
}
|
||||
|
||||
|
|
@ -48,7 +48,7 @@ public class XpFormula {
|
|||
* @param currentLevel текущий уровень
|
||||
* @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 xpForNextLevel = getTotalXPForLevel(currentLevel + 1);
|
||||
int xpNeeded = xpForNextLevel - xpForCurrentLevel;
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ public class MessageListener extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onMessageReceived(MessageReceivedEvent event) {
|
||||
public void onMessageReceived(final MessageReceivedEvent event) {
|
||||
try {
|
||||
if (!event.getAuthor().isBot()) {
|
||||
String userId = event.getAuthor().getId();
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ public class ResetLevelsButtonHandler extends ListenerAdapter {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onButtonInteraction(ButtonInteractionEvent event) {
|
||||
public void onButtonInteraction(final ButtonInteractionEvent event) {
|
||||
String buttonId = event.getComponentId();
|
||||
|
||||
if (buttonId.startsWith(PREFIX_CONFIRM)) {
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue